package cn.edu.xjtu.nbrash.xbarsuite.utilities;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

public class Utilities {

	public static final String TAG = Utilities.class.getName();

	/**
	 * Convert android.graphics.Bitmap to com.google.zxing.BinaryBitmap
	 * 
	 * @param bitmap
	 * @return com.google.zxing.BinaryBitmap
	 */
	public static BinaryBitmap bitmap2BinaryBitmap(Bitmap bitmap) {
		BinaryBitmap binaryBitmap = null;
		if (bitmap != null) {
			int[] pixels = Utilities.getPixelsFromBitmap(bitmap);
			RGBLuminanceSource rgbLuminanceSource = new RGBLuminanceSource(
					bitmap.getWidth(), bitmap.getHeight(), pixels);
			binaryBitmap = new BinaryBitmap(new HybridBinarizer(
					rgbLuminanceSource));
		}
		return binaryBitmap;
	}

	/**
	 * Get all pixels within a int array from android.graphics.Bitmap
	 * 
	 * @param bitmap
	 * @return pixels of the bitmap
	 */
	public static int[] getPixelsFromBitmap(Bitmap bitmap) {
		int[] pixels = null;
		if (bitmap != null) {
			pixels = new int[bitmap.getWidth() * bitmap.getHeight()];
			bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0,
					bitmap.getWidth(), bitmap.getHeight());
		}
		return pixels;
	}

	/**
	 * Convert android.graphics.Bitmap to android.net.Uri
	 * 
	 * @param context
	 * @param bitmap
	 * @param title
	 * @param description
	 * @return Uri of the bitmap
	 */
	public static Uri bitmap2Uri(String tempPath, Bitmap bitmap) {
		try {
			bitmap.compress(Bitmap.CompressFormat.PNG, 80,
					new FileOutputStream(tempPath));
			return Uri.fromFile(new File(tempPath));
		} catch (FileNotFoundException e) {
			Log.e(TAG, e.toString());
			e.printStackTrace();
		}
		return null;
	}
}
